//
//  CAScanerViewController.m
//  LNH
//
//  Created by twentylx on 2018/2/26.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAScanerViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface CAScanerViewController () <AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCaptureDeviceInput *input;
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;

@property (nonatomic, weak) UIView *maskView;

@end

@implementation CAScanerViewController


#pragma mark - Initial Methods
/// 初始化数据
- (void)lm_initialDefaultsForController {
    [self setupCamera];
    [self setupScanPreviewView];
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
    
}

/// 创建视图
- (void)lm_createViewForController {
    
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    [self.navigationItem setTitle:@"扫一扫"];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

#pragma mark - Target Mehtods

-(void) backAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void) openAlbumAction {
    
}

#pragma mark - Setter & Getter

- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc] init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input]) {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output]) {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode] ;
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.bounds;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [_session startRunning];
}

- (void)setupScanPreviewView
{
    UIImageView *scanView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [scanView setImage:[UIImage imageNamed:@"QR_code_frame"]];
    scanView.clipsToBounds = YES;
    [self.view addSubview:scanView];
    
    [scanView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-60, SCREEN_WIDTH-60));
    }];
    
    UIImageView *scanNetImageView = [[UIImageView alloc] initWithFrame:(CGRect){ 5, -(SCREEN_WIDTH-60), SCREEN_WIDTH-70, SCREEN_WIDTH-60 }];
    [scanNetImageView setImage:[UIImage imageNamed:@"scan_net"]];
    
    CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
    scanNetAnimation.keyPath = @"transform.translation.y";
    scanNetAnimation.byValue = @(SCREEN_WIDTH-60);
    scanNetAnimation.duration = 1.5;
    scanNetAnimation.repeatCount = MAXFLOAT;
    [scanNetImageView.layer addAnimation:scanNetAnimation forKey:nil];
    [scanView addSubview:scanNetImageView];
    
    UILabel *titleLabel = [UILabel new];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    [titleLabel setFont:FS(14)];
    [titleLabel setTextColor:[UIColor whiteColor]];
    [titleLabel setText:@"将取景框对准二维码，即可自动扫描"];
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(scanView.mas_bottom).offset(10);
        make.left.right.equalTo(self.view);
    }];
    
}


#pragma mark - Private Method


#pragma mark - Public Method


#pragma mark - Other Delegate

#pragma mark AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    NSString *stringValue;
    
    if ([metadataObjects count] >0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    [_session stopRunning];
    
    if ([self.delegate respondsToSelector:@selector(scanWithQRCode:)]) {
        [self.delegate scanWithQRCode:stringValue];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end

